package com.telit.firecommand.service;

import com.alibaba.excel.EasyExcel;
import com.telit.common.exception.ForestBaseException;
import com.telit.firecommand.listener.EasyExcelConsumerListener;
import com.telit.firecommand.model.easyExcel.FirePointExcel;
import com.telit.firecommand.util.UnZipUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Auther amy
 * @Describe 过火点位业务层
 */
@Service
public class FirePointService {

    public List<List<String>> getDataFormExcel(MultipartFile file)throws IOException {
        // 获取监听对象
        EasyExcelConsumerListener<FirePointExcel> firePointReaderListener = new EasyExcelConsumerListener<>();
        // 读取文件
        EasyExcel.read(file.getInputStream(),FirePointExcel.class,firePointReaderListener).sheet().doRead();
        // 获取文件数组
        List<FirePointExcel> list = firePointReaderListener.getDatas();
        // 将集合对象转成集合数组
        List<List<String>> resultList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(firePointExcel -> {
                List<String> simpleList = new ArrayList<>();
                simpleList.add(firePointExcel.getLongitude());
                simpleList.add(firePointExcel.getLatitude());
                resultList.add(simpleList);
            });
        }
        return resultList;
    }

    /**
     * 从压缩文件中获取
     * @param file
     * @return
     * @throws IOException
     */
    public List<String> getDataFromZip(MultipartFile file) throws IOException {
        // 将MultipartFile转换成file,"."是特殊字符
        String originalFilename = file.getOriginalFilename();
        List<String> filename = Arrays.asList(originalFilename.split("\\."));
        File newFile = File.createTempFile(filename.get(0), filename.get(1));
        file.transferTo(newFile);

        // 获取内存中解压的文件地址集合
        List<String> filePathList = UnZipUtils.batchadd(newFile);
        List<String> list = new ArrayList<>();

        // 获取shp文件中的经纬度
        if(CollectionUtils.isEmpty(filePathList)){
            throw new ForestBaseException("文件解析失败");
        }
        // 判断是否存在.shp文件
        boolean flag = true;
        for (String filePath:filePathList) {
            if (filePath.endsWith(".shp")) {
                try {
                    list = UnZipUtils.getCoordinateFromShape(filePath);
                    flag = false;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if(flag){
            throw new ForestBaseException("该文件解压没有.shp文件");
        }
        return list;
    }
}
